#!/bin/bash -e

echo "[$(hostname -s)] start ceph-osd in $(hostname -s) ..."
OSDID=`uuidgen`
OSD_SECRET=$(ceph-authtool --gen-print-key)
OSD_NUM=$(echo "{\"cephx_secret\": \"$OSD_SECRET\"}" | \
   sudo ceph osd new $OSDID -i - \
   -n client.bootstrap-osd -k /var/lib/ceph/bootstrap-osd/ceph.keyring)
echo "[$(hostname -s)] get osd.num = $OSD_NUM ..."
if [ ! -d "/dev/ceph-osds" ]; then
    sudo dd if=/dev/zero of=/var/local/osd$OSD_NUM.img bs=4M count=16384 oflag=direct
    sudo sgdisk -g --clear /var/local/osd$OSD_NUM.img
    sudo vgcreate -y ceph-osds $(sudo losetup --show -f /var/local/osd$OSD_NUM.img)
    sudo lvcreate -l 100%VG -n osd$OSD_NUM ceph-osds
fi
sudo mkdir -p /var/lib/ceph/osd/ceph-$OSD_NUM
sudo mkfs.xfs /dev/ceph-osds/osd$OSD_NUM -f > /dev/null
sudo mount /dev/ceph-osds/osd$OSD_NUM /var/lib/ceph/osd/ceph-$OSD_NUM
sudo ceph-authtool --create-keyring /var/lib/ceph/osd/ceph-$OSD_NUM/keyring --name osd.$OSD_NUM --add-key $OSD_SECRET | sed "s/^/[$(hostname -s)] &/g"
sudo ceph-osd -i $OSD_NUM --mkfs --osd-uuid $OSDID  > /dev/null 2>&1
sudo ceph-osd -i $OSD_NUM  > /dev/null 2>&1
echo "[$(hostname -s)] finish start ceph-osd.$OSD_NUM in $(hostname -s)"